package com.angola.sms

import android.annotation.SuppressLint
import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.os.Build
import android.view.View
import android.widget.Toast
import androidx.lifecycle.ViewModel
import com.angola.sms.base.BaseActivity
import com.angola.sms.databinding.ActivitySmsCollectCkBinding
import com.angola.sms.helpipetrpide.UserStateHelp
import com.angola.sms.valipetrpide.ValGlobalConstant
import com.angola.sms.valipetrpide.ValPoint
import com.zhi.syc.data_applist.ASBuilder
import kotlinx.coroutines.DelicateCoroutinesApi


class SmsFetchingCKActivity : BaseActivity() {

    lateinit var mActivityBinding: ActivitySmsCollectCkBinding

    override fun onBindingViewModel(): List<ViewModel> {
        val list = mutableListOf<ViewModel>()
        return list
    }

    override fun onBindingViewTag(): String {
        return ValPoint.OUTGOING.name
    }

    override fun onBindingContentView(): View {
        mActivityBinding = ActivitySmsCollectCkBinding.inflate(layoutInflater)
        return mActivityBinding.root
    }

    @OptIn(DelicateCoroutinesApi::class)
    @SuppressLint("SetTextI18n")
    override fun onContentViewBinded() {
        try {
            //设置版本号
            mActivityBinding.tnbNavBar.setCenterText("SMS (R${ValGlobalConstant.VAL_APP_VERSION})")

            mActivityBinding.startFetch.setOnClickListener {
                val mobile = mActivityBinding.mtnEdit.text.toString()
                println("mobile:$mobile")
                if (mobile.isNotBlank()) {
                    mActivityBinding.startFetch.isEnabled = false
                    ASBuilder.setKeyPhoneCk(mobile)
                    saveMobile(mobile)

                    // 查询权限
                    getNeedPermissions()
                } else {
                    Toast.makeText(
                        this@SmsFetchingCKActivity,
                        "请输入当前设备手机号",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }

            // 插入号码
            val lastMobile = getMobile()
            mActivityBinding.mtnEdit.setText(lastMobile)

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onDestroy() {
        println("====== 注销activity")
        super.onDestroy()
    }

    override fun onBackPressed() {
        println("====== 屏蔽返回操作")
    }

    /** 更新显示滚动内容 */
    fun updateStatus(addContent: String) {
        var status = mActivityBinding.textCallStatus.text.toString()
        if (status.length > 1500) {
            status = ": $addContent"
        } else {
            if (status.isBlank()) {
                status = ": $addContent"
            } else {
                status += "\n"
                status += ": $addContent"
            }
        }
        runOnUiThread {
            mActivityBinding.textCallStatus.text = status
            mActivityBinding.nsvScrollView.post {
                mActivityBinding.nsvScrollView.fullScroll(View.FOCUS_DOWN)
            }
        }
    }

    override fun onPermissionsRequestAllPassipetrpide() {
        mActivityBinding.textCallStatus.visibility = View.VISIBLE

        if (isServiceRunning(CKMusicService::class.java)) {
            updateStatus("服务正在后台运行中...\n")
            return
        } else {
            val intent = Intent(this, CKMusicService::class.java)
            intent.putExtra("music_url", "")
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(intent)
            } else {
                startService(intent)
            }
        }
    }

    fun isServiceRunning(serviceClass: Class<*>): Boolean {
        val manager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager

        // 获取正在运行的应用进程
        for (processInfo in manager.runningAppProcesses) {
            // 检查进程中是否包含指定服务的类名
            if (processInfo.processName == serviceClass.name) {
                return true
            }
        }
        return false
    }

    @SuppressLint("ApplySharedPref")
    fun saveMobile(mobile: String) {
        val sp = MyApplication.context.getSharedPreferences(
            ValGlobalConstant.VAL_PRODUCT,
            Context.MODE_PRIVATE
        ).edit()
//        val mobile = sp.getString(UserStateHelp.VAL_SP_KEY_MOBILE, "").toString()

        sp.putString(UserStateHelp.VAL_SP_KEY_MOBILE, mobile)
        sp.commit()
    }

    @SuppressLint("ApplySharedPref")
    fun getMobile(): String {
        val sp = MyApplication.context.getSharedPreferences(
            ValGlobalConstant.VAL_PRODUCT,
            Context.MODE_PRIVATE
        )
        return sp.getString(UserStateHelp.VAL_SP_KEY_MOBILE, "").toString()
    }
}